<?php


namespace app\api\controller;


use app\common\controller\Api;
use app\common\library\Sms;
use app\common\model\Business;
use app\common\model\GoodsCards;
use app\common\model\GoodsTag;
use app\common\model\Hospital;
use app\common\model\Hospitalappoint;
use app\common\model\Hospitaltimes;
use app\common\model\order\Order;
use app\common\model\order\OrderItem;
use app\common\model\user\Appoints;
use app\common\model\UserCards;
use think\Db;
use think\Model;
use think\Validate;

class Appoint extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = [];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     * 预约
     */
    public function addAppointment()
    {
       $params = $this->request->param('');
        $mobile = $this->request->post('appoint_mobile');
        $captcha = $this->request->post('appoint_code');
        if (!$mobile ) {
            $this->error(__('请填写手机号'));
        }
//        if (!$captcha) {
//            $this->error(__('请填写验证码'));
//        }
//
//        if (!Validate::regex($mobile, "^1\d{10}$")) {
//            $this->error(__('Mobile is incorrect'));
//        }
//        if (!Sms::check($mobile, $captcha, 'notice')) {
//            $this->error(__('Captcha is incorrect'));
//        }
       $params['user_id']=$this->auth->id;
       $params['user_info']=(new \app\admin\model\User())->where(['id'=>$this->auth->id])->find();
       $data =(new Appoints())->saveAppionts($params);

       if($data['code']==200){
           $this->success('');
       }else{
           $this->error($data['msg']);
       }
    }

    public function updateAppointment()
    {
        $params = $this->request->param('');

        $params['user_id']=$this->auth->id;
        $params['user_info']=(new \app\admin\model\User())->where(['id'=>$this->auth->id])->find();
        $data =(new Appoints())->updateAppionts($params);
        if($data['code']==200){
            $this->success('');
        }else{
            $this->error('预约失败');
        }
    }

    public function getAppoints()
    {
        $params= $this->request->param('');
        $mdata= Hospitalappoint::where(['hospital_id'=>$params['hospital_id']])->order(['week_days'=>'asc','startime'=>'asc'])->select();
        $weeks=Hospitalappoint::where(['hospital_id'=>$params['hospital_id']])->order(['week_days'=>'asc','startime'=>'asc'])
            ->group('week_days')
            ->column('week_days');

        $times=[];
        foreach ($mdata as $k=>$v){

            $startime=explode(':',$v['startime']);
            $endtime=explode(':',$v['endtime']);
            $times[$v['week_days']][] = ['start_hours'=>intval($startime[0]),
                'end_hours'=>intval($endtime[0]),
                'startime'=>$startime[0].':'.$startime[1],
                'endtime'=>$endtime[0].':'.$endtime[1],
                'startime_text'=>$v['startime'],
                'endtime_text'=>$v['endtime'],
                'time_solt'=>$startime[0].':'.$startime[1].'-'.$endtime[0].':'.$endtime[1]];
        }
        //strtotime(" +1 hour ")
        $showtime=strtotime(" +3 day ");

        $data=[];
        if(count($mdata)>0) {
            $m = 0;


            while (count($data) < 7) {
                $time = strtotime($m . " day");

                $week_days =date('w', $time);
                 if($week_days==0){
                     $week_days=7;
                 }
                if (in_array($week_days, $weeks)) {
                    $ems= $times[$week_days];
                    $mtimes=[];
                    foreach ($ems as $k1=>$v1)
                    {
                        if($showtime<strtotime(date('Y-m-d', $time).$v1['startime_text'])){
                            $mtimes[]=$v1;
                        }
                    }
                    if(count($mtimes)>0){
                        $data[] = ['week_name' =>$this->checkdays(date('w', $time)),'date' => date('Y-m-d', $time),
                            'date_min' => date('m.d', $time),'times_arr' => $mtimes];
                    }
//                    if ($m == 0) {
//
//
//                    } else {
//                        $data[] = ['week_name' =>$this->checkdays(date('w', $time)),'date' => date('Y-m-d', $time),
//                            'date_min' => date('m.d', $time),'times_arr' => $times[$week_days]];
//                    }
                }
                $m++;
            }

        }
        $this->success('',$data);


    }

    public function checkpoint()
    {
        $params=$this->request->param();
        $where=['appoints.user_id'=>$this->auth->id,'appoints.id'=>$params['id']];
        $data = (new Appoints())->with(['hospital'])->where($where)->find();
        if($data){
             if($data['appoint_startime']<=time()){
                 \app\common\model\order\Order::where(['id'=>$params['id']])
                     ->update(['status'=>-1]);
                 $this->error('预约已失效');
             }else{
                 $this->success('');
             }
        }else{
            $this->error('预约不存在');
        }
    }

    public function checkdays($week)
    {
          switch ($week){
              case 0:
                  return '周日';
                  break;
              case 7:
                  return '周日';
                  break;
              case 1:
                  return '周一';
                  break;
              case 2:
                  return '周二';
                  break;
              case 3:
                  return '周三';
                  break;
              case 4:
                  return '周四';
                  break;
              case 5:
                  return '周五';
                  break;
              case 6:
                  return '周六';
                  break;
              default:
                  return '';
                  break;
          }
    }

    public function hospitalDetail()
    {
        $param =$this->request->param('');
        $lat = $this->request->param('lat');
        $lng = $this->request->param('lng');
        if(empty($lat)){
            $data= (new Hospital())
                ->where(['id'=>$param['id']])

                ->find();
            $data['distance']='';
        }else{
            $data= (new Hospital())
                ->where(['id'=>$param['id']])
                ->field("*, getDistance(lng, lat, {$lng}, {$lat}) as distance")
                ->find();
        }


        if($data){
            $startime1=explode(':',$data['startime']);
            $endtime1=explode(':',$data['endtime']);

            $data['time_text']=$startime1[0].':'.$startime1[1].'-'.$endtime1[0].':'.$endtime1[1];
            if(empty($data['distance'])){
               $data['distance']='未知';
            }else{
                if($data['distance']<1000){
                    $data['distance']=ceil($data['distance']).'m';
                }else{
                    $data['distance']=round($data['distance']/1000,2).'km';
                }
            }

            $times_arr=Hospitaltimes::where(['hospital_id'=>$param['id']])
                ->order(['startime'=>'asc'])
                ->field('id,startime,endtime,week_days,week_name')
                ->select();
            // dump($orders_w);

            $times=[];
            foreach ($times_arr as $k => $v) {
                $startime=explode(':',$v['startime']);
                $endtime=explode(':',$v['endtime']);
               // $times_arr[$k['times']]=$startime[0].':'.$startime[1].'-'.$endtime[0].':'.$endtime[1];

               $times[$v['week_name']][] = ['time_solt'=>$startime[0].':'.$startime[1].'-'.$endtime[0].':'.$endtime[1]];
            }
            $mtimes = [];
            foreach ($times as $k=>$v){
//                $m1=explode(',',$k);
//                $ms=[];
//                foreach ($m1 as $k1=>$v1){
//                    $m=$k;
//                    if($m==7){
//                        $m=0;
//                    }
//                   $ms[]= $this->checkdays($k1);
//                }

//
                $time_solt =[];
                foreach ($v as $k1=>$v1){
                    $time_solt[]=$v1['time_solt'];
                 }

                $mtimes[]=['times'=>$time_solt,'week_name'=>$this->checkweeks($k)];

            }


            $data['mtimes']=$mtimes;

        }
        $this->success('',$data);
    }


    public function checkweeks($week)
    {
        switch ($week){
            case '周一,周二,周三,周四,周五':
                return '周一至周五';
                break;
            case '周一,周二,周三,周四,周五,周六':
                return '周一至周六';
                break;
            case '周一,周二,周三,周四,周五,周六,周日':
                return '周一至周日';
                break;
            default:
                return $week;
                break;
        }
    }
function is_duplicate($arr,$value){
$column=array_column($arr,0);
return in_array($value,$column);
}


    /**
     * 预约列表
     */
    public function appointsList()
    {
      $param =$this->request->param('');
      $where['appoints.user_id']=$this->auth->id;
      if(!empty($param['status'])){
         if($param['status']==1){
             $where['appoints.status']=0;
         }else if($param['status']==2){
             $where['appoints.status']=1;
         }else if($param['status']==3){
             $where['appoints.status']=-1;
         }
      }

      $data = (new Appoints())->with(['hospital'])->where($where)->order(['appoints.createtime'=>'desc'])->paginate();
      $this->success('',$data);
    }

    public function cancelpoint()
    {
        $param =$this->request->param('');
        $where=['user_id'=>$this->auth->id,'status'=>0,'id'=>$param['id']];
        $data = (new Appoints())->where($where)->find();
        Db::startTrans();
        if($data){

            $card = (new UserCards())->where(['id'=>$data['card_id']])->find();
            if($card['can_uses']==0){
                (new UserCards())->where(['id'=>$data['card_id']])->update(['status'=>1]);
                Order::where(['id'=>$data['order_id']])->update(['status'=>1,'order_status'=>1]);
            }
            $res = (new Appoints())->where($where)
                ->update(['status'=>-1,'cancel_time'=>time(),'updatetime'=>time()]);
            (new UserCards())->where(['id'=>$data['card_id']])->setInc('can_uses');
            (new UserCards())->where(['id'=>$data['card_id']])->setDec('used_nums');
            Order::where(['id'=>$data['order_id']])->setInc('canuse_appoints');
            Order::where(['id'=>$data['order_id']])->setDec('used_appoints');
            OrderItem::where(['id'=>$data['order_item_id']])->setInc('canuse_num');
            OrderItem::where(['id'=>$data['order_item_id']])->setDec('used_num');
            GoodsTag::where(['id'=>$data['tag_id']])->setDec('appoints');
           if($res){
               Db::commit();
                $this->success('',$res);
            }else{
               Db::rollback();
                $this->error('预约取消失败');
            }
        }else{
            $this->error('不存在该预约中订单');
        }

    }

    /**
     * 预约详情
     */
    public function appointDetail()
    {
        $params =$this->request->param('');
        $where=['appoints.user_id'=>$this->auth->id,'appoints.id'=>$params['id']];
        $data = (new Appoints())->with(['hospital'])->where($where)->find();
        if($data){
            $data['rights_tags']=explode(',',$data['rights_tags']);
            $data['userinfo']=\app\common\model\User::getmine(['id'=>$this->auth->id]);
        }
        $this->success('',$data);
    }
    /**
     * 权益列表
     */
    public function hospitalList()
    {
        $param =$this->request->param();
        if(!empty($param['card_id'])){
            $this->error('参数错误');
        }
        $cards=(new UserCards())->where(['id'=>$param['card_id'],'user_id'=>$this->auth->id])->find();
        if(!$cards){
            $this->error('未查询到数据');
        }
        $where=['status'=>1,'id'=>['in',$cards['hospital_ids']]];
        if(!empty($param['area_id'])){
            $where['area_id']=$param['area_id'];
        }
        $lat = $this->request->param('lat');
        $lng = $this->request->param('lng');
        $where=[];
        $district=$this->request->param('district','');
        if (!empty($district)){
            $district_id=db('marea')->where(['name'=>$district,'level'=>3])->value('id');
            $where['area_id']=$district_id;
            //  $where['_string'] = "getDistance(lng, lat, {$lng}, {$lat})<{$distance}";
        }
        $data  =Hospital::field("*, getDistance(lng, lat, {$lng}, {$lat}) as distance")
            ->where(['status'=>1])
            ->where($where)
            ->order(['distance'=>'asc','weigh'=>'desc','id'=>'desc'])
            ->paginate();
        foreach ($data as $k=>$v){

            if($v['distance']<1000){
                $data[$k]['distance']=ceil($v['distance']).'m';
            }else{
                $data[$k]['distance']=round($v['distance']/1000,2).'km';
            }

        }
        $this->success('',$data);
        //$data=(new UserCards())->where($where)->paginate();

    }
    /**
     * 权益列表
     */
    public function rightsList()
    {
        \app\common\model\order\Order::where(['status'=>1])
            ->where('order_date','<=',time())
            ->update(['status'=>2,'order_status'=>2]);
        UserCards::where(['status'=>1])
            ->where('rights_endtime','<=',time())
            ->update(['status'=>4]);
        $where=['user_id'=>$this->auth->id,'status'=>['in',[1,2,4]]];
        $data=(new UserCards())->with(['services'])->where($where)->order(['createtime'=>'desc'])->paginate();
        $this->success('',$data);
    }

    /**
     * 权益详情
     */
    public function rightsDetail()
    {

        \app\common\model\order\Order::where(['status'=>1])
            ->where('order_date','<=',time())
            ->update(['status'=>2,'order_status'=>2]);
        UserCards::where(['status'=>1])
            ->where('rights_endtime','<=',time())
            ->update(['status'=>4]);
        $param =$this->request->param();
        $data =(new UserCards())->with(['services'])->where(['id'=>$param['id']])->find();
        $this->success('',$data);
    }

    /**
     *
     */
    public function sure_activate()
    {
        $params = $this->request->post('');
        if(empty($params['card_key'])){
            $this->error('','参数错误');
        }
       $exist= (new GoodsCards())->with(['goods'])
           ->where(['goods_card_key'=>$params['card_key']])
           ->where(['goods_cards.status'=>1,'goods.status'=>1])
           ->where('goods.id is not null')
           ->find();
       $mcount= \db('activate_errors')->where(['user_id'=>$this->auth->id])
            ->whereTime('createtime','today')->count();
       if($mcount>=10){
           $this->error('','输错次数已达上限，请明天再来');
       }

        if(!$exist){
            \db('activate_errors')->insert(['user_id'=>$this->auth->id,'createtime'=>time()]);
            $this->error('','该卡不存在');
        }
        if($exist['use_status']==1){
            \db('activate_errors')->insert(['user_id'=>$this->auth->id,'createtime'=>time()]);
            $this->error('','该卡已激活');
        }
        Db::startTrans();

        (new GoodsCards())->where(['goods_card_key'=>$params['card_key']])->update(['use_status'=>1,'user_id'=>$this->auth->id,'use_time'=>time()]);
        $tags=db('goods_tags')
            ->where('id','in',$exist['goods']['rights_tags'])
            ->group('tag_name')->column('tag_name');
        if($exist['goods']['enddate']<time()){
            $this->error('','权益已失效');
        }
        if($exist['business_id']){
            Business::where(['id'=>$exist['business_id']])->setInc('used_nums',$exist['goods']['rights_num']);
            Business::where(['id'=>$exist['business_id']])->setDec('store_num',$exist['goods']['rights_num']);
        }

        $data3['tags']=implode(',',$tags);
        $tags_names=GoodsTag::where('id','in',$exist['goods']['tag_ids'])->column('tag_name');
        $tags_names=implode(',',$tags_names);
        $saves=['user_id'=>$this->auth->id,'order_item_id'=>0,
            'order_id'=>0,'hospital_ids'=>$exist['goods']['hospital_ids'],
            'goods_id'=>$exist['goods_id'],'card_id'=>$exist['id'],
            'type'=>2,
            'tag_ids'=>$exist['goods']['tag_ids'],
            'tag_names'=>$tags_names,
            'business_id'=>$exist['business_id'],
            'goods_card_key'=>$exist['goods_card_key'],
            'rights_card'=>$exist['goods']['rights_card'],'rights_title'=>$exist['goods']['rights_title'],
            'rights_nums'=>$exist['goods']['rights_num'],'can_uses'=>$exist['goods']['rights_num'],
            'rights_endtime'=>$exist['goods']['enddate'],'rights_content'=>$exist['goods']['rights_content'],
            'rights_memo'=>$exist['goods']['rights_memo'],
            'rights_desc'=>$exist['goods']['rights_desc'],
            'is_all'=>$exist['goods']['is_all'],
            'rights_tags'=>implode(',',$tags),
            'status'=>1,'createtime'=>time(),'updatetime'=>time()
        ];


        $card_id=(new UserCards())->insertGetId($saves);
        if($card_id){
           $tags_ids= explode(',',$exist['goods']['tag_ids']);
           $m_saves=[];
           $createtime=time();
           foreach ($tags_ids as $k=>$v){
               $mid=\db('goods_tags')->where(['id'=>$v])->value('tag_name');
               if(!$mid){
               }else{
                   $m_saves[]=['user_id'=>$this->auth->id,
                       'card_id'=>$card_id,'tag_id'=>$v,
                       'tag_name'=>$mid,'createtime'=>$createtime];
               }
           }
           \db('user_card_examines')->insertAll($m_saves);

            Db::commit();
            $this->success('',$card_id);
        }else{
            Db::rollback();
            $this->error('','激活失败');
        }
       ;



    }
}